using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using OSCSchema;

namespace OSC.Base
{
    internal class OSCSerializer : IOSCSerializer
    {
        public string Serialize(object o)
        {
            var writer = new StringWriter();
            var t = o.GetType();
            var serializer = new XmlSerializer(t);
            serializer.Serialize(writer, o);

            return writer.ToString();
        }
        public T Deserialize<T>(string s)
        {
            try
            {
                return (T)(new XmlSerializer(typeof(T), string.Empty).Deserialize(new StringReader(s)));
            }
            catch
            {
                try
                {
                    return (T)(new XmlSerializer(typeof(T), string.Empty).Deserialize(new StringReader(s)));
                }
                catch
                {

                    return default(T);
                }
            }
        }
        public hashedAddresses DeserializeHashedAddresses(string s)
        {
            var foo = XDocument.Parse(s).Descendants("hashedAddress")
                                                .Select((el, index) =>
                                                          new personAddressType
                                                                            {
                                                                                hashedAddress = new[] { el.Value },
                                                                                index = index
                                                                            }
                                                   ).ToArray();

            var bar = new hashedAddresses
                          {
                              personAddresses = foo
                          };
            return bar;
        }
    }
}